package com.yzt.message.custom;

import static com.yzt.message.MessageConstants.TYPE_ACCOUNT_PAY;
import static com.yzt.message.MessageConstants.TYPE_ACCOUNT_SYSTEM;
import static com.yzt.message.MessageConstants.TYPE_INTERACTIVE_MESSAGE;
import static com.yzt.zhuju.rongyun.IMMessageType.GROUP_CREATE;
import static com.yzt.zhuju.rongyun.IMMessageType.GROUP_EDIT_NAME;
import static com.yzt.zhuju.rongyun.IMMessageType.GROUP_JOIN_MESSAGE;
import static com.yzt.zhuju.rongyun.IMMessageType.GROUP_KICK;
import static com.yzt.zhuju.rongyun.IMMessageType.GROUP_QUIT_MESSAGE;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.yzt.p_base.utils.DisplayUtils;
import com.yzt.plugin_widget.RoundImageView;
import com.yzt.zhuju.network.entity.message.ContentTranslateBean;
import com.yzt.zhuju.network.entity.user.GroupProfileUser;
import com.yzt.zhuju.richtext.EmojiTextView;
import com.yzt.zhuju.widget.tuiview.TUITextView;
import com.yzt.message.MessageConstants;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.message.MessageExtraInfo;
import com.yzt.message.R;
import com.yzt.message.UnReplyMessageUtils;

import java.util.List;

import io.rong.imkit.config.RongConfigCenter;
import io.rong.imkit.conversation.extension.component.emoticon.AndroidEmoji;
import io.rong.imkit.conversationlist.model.BaseUiConversation;
import io.rong.imkit.conversationlist.model.GatheredConversation;
import io.rong.imkit.conversationlist.provider.PrivateConversationProvider;
import io.rong.imkit.model.UiMessage;
import io.rong.imkit.utils.RongDateUtils;
import io.rong.imkit.widget.adapter.IViewProviderListener;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.imlib.model.MessageContent;
import io.rong.message.HQVoiceMessage;

/**
 * 会话列表适配器
 */
@SuppressLint("UseCompatLoadingForDrawables")
public class CustomConversationProvider extends PrivateConversationProvider {

    protected static class ViewHolder extends io.rong.imkit.widget.adapter.ViewHolder {

        public TextView title;
        public TextView mTopTv;
        public TextView time;
        public EmojiTextView content;
        public ImageView ivTop;

        public ViewHolder(Context context, View result) {
            super(context, result);
            this.title = result.findViewById(R.id.rc_conversation_title);
            this.time = result.findViewById(R.id.rc_conversation_date);
            this.mTopTv = result.findViewById(R.id.top_tv);
            this.ivTop = result.findViewById(R.id.iv_top);
            this.content = result.findViewById(R.id.rc_conversation_content);
        }
    }

    @Override
    public boolean isItemViewType(BaseUiConversation item) {
        //根据业务需要，判断 item 是该模板需要处理的会话时，返回 true, 否则返回 false
        //此处以自定义私聊会话模板为例
        return item.mCore.getConversationType().equals(Conversation.ConversationType.PRIVATE);
    }

    @Override
    public io.rong.imkit.widget.adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        //根据业务需要，自定义处理
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nomi_rc_item_base_conversation, parent, false);
        return new ViewHolder(parent.getContext(), view);
    }

    @Override
    public void bindViewHolder(io.rong.imkit.widget.adapter.ViewHolder viewHolder, BaseUiConversation uiConversation, int position,
                               List<BaseUiConversation> list, IViewProviderListener<BaseUiConversation> listener) {
        if (!(viewHolder instanceof ViewHolder)) {
            return;
        }

        ViewHolder holder = (ViewHolder) viewHolder;

        // 会话对象为空则不加载
        if (uiConversation == null) {
            holder.title.setText(null);
            holder.time.setText(null);
            holder.content.setText(null);
            return;
        }

        // 头像的点击事件
        holder.getView(R.id.rc_conversation_portrait).setOnClickListener(v -> {
            if (RongConfigCenter.conversationListConfig().getListener() != null) {
                if (uiConversation.mCore.getTargetId().equals(MessageConstants.TYPE_NOMI_SERVICE)) {
                    return;
                }
                RongConfigCenter.conversationListConfig().getListener().onConversationPortraitClick(holder.getContext(), uiConversation.mCore.getConversationType(), uiConversation.mCore.getTargetId());
            }
        });

        //设置系统用户的标题和内容
        setTitle(uiConversation, holder.getContext());

        Conversation conversation = uiConversation.mCore;
        String conversationTitle = uiConversation.mCore.getConversationTitle();
        MessageContent messageContent = uiConversation.mCore.getLatestMessage();
        boolean isGather = uiConversation instanceof GatheredConversation;

        //设置会话标题
        holder.title.setText(conversationTitle);

        int defaultId = R.mipmap.icon_placeholder;
        if (uiConversation.mCore.getConversationType().equals(Conversation.ConversationType.CHATROOM)) {
            defaultId = R.drawable.rc_default_chatroom_portrait;
        } else if (uiConversation.mCore.getConversationType().equals(Conversation.ConversationType.CUSTOMER_SERVICE)) {
            defaultId = R.drawable.rc_default_chatroom_portrait;
        }

        int isDefaultIcon = defaultId;

        // 获取系统匹配头像
        defaultId = getSystemDefaultId(uiConversation, defaultId);
        Glide.with(holder.getContext()).clear((ImageView) holder.getView(R.id.rc_conversation_portrait));
        //设置头像
        holder.getView(R.id.rl_group_header).setVisibility(View.GONE);
        holder.getView(R.id.rl_group_header).setVisibility(View.VISIBLE);
        holder.getView(R.id.rc_conversation_portrait).setVisibility(View.GONE);
        RoundImageView portrait1 = holder.getView(R.id.rc_conversation_portrait1);
        portrait1.setVisibility(View.GONE);
        RoundImageView portrait2 = holder.getView(R.id.rc_conversation_portrait2);
        portrait2.setVisibility(View.GONE);
        RoundImageView portrait3 = holder.getView(R.id.rc_conversation_portrait3);
        portrait3.setVisibility(View.GONE);
        RoundImageView portrait4 = holder.getView(R.id.rc_conversation_portrait4);
        portrait4.setVisibility(View.GONE);
        holder.getView(R.id.rc_conversation_user_count).setVisibility(View.GONE);

        if (uiConversation.mCore.getConversationType().equals(Conversation.ConversationType.PRIVATE) &&
                !TextUtils.isEmpty(uiConversation.mCore.getPortraitUrl()) && isDefaultIcon == defaultId) {
            ImageLoadUtil.loadIv(holder.getContext(), uiConversation.mCore.getPortraitUrl(),
                    holder.getView(R.id.rc_conversation_portrait), defaultId);
            holder.getView(R.id.rc_conversation_portrait).setVisibility(View.VISIBLE);
            holder.getView(R.id.rl_group_header).setVisibility(View.GONE);
        } else {
            // 群聊
            if (uiConversation.mCore.getConversationType().equals(Conversation.ConversationType.GROUP)) {
                List<GroupProfileUser> listGroup = null;
                try {
                    listGroup = JSONArray.parseArray(uiConversation.mCore.getPortraitUrl(), GroupProfileUser.class);
                } catch (Exception ignored) {

                }
                if (listGroup == null || listGroup.isEmpty()) {
                    defaultId = R.drawable.rc_default_group_portrait;
                } else if (listGroup.size() == 1) {
                    holder.getView(R.id.rc_conversation_portrait).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rl_group_header).setVisibility(View.GONE);
                } else {
                    holder.getView(R.id.rc_conversation_portrait).setVisibility(View.GONE);
                    holder.getView(R.id.rl_group_header).setVisibility(View.VISIBLE);
                }
                if (listGroup == null || listGroup.isEmpty()) {
                    defaultId = R.drawable.rc_default_group_portrait;
                } else if (listGroup.size() == 1) {
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(0).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait), defaultId);
                } else if (listGroup.size() == 2) {
                    holder.getView(R.id.rc_conversation_portrait1).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait4).setVisibility(View.VISIBLE);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(0).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait1), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(1).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait4), defaultId);
                    RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) portrait1.getLayoutParams();
                    layoutParams1.height = DisplayUtils.dp2px(34f);
                    layoutParams1.width = DisplayUtils.dp2px(34f);
                    portrait1.setLayoutParams(layoutParams1);
                    RelativeLayout.LayoutParams layoutParams4 = (RelativeLayout.LayoutParams) portrait4.getLayoutParams();
                    layoutParams4.height = DisplayUtils.dp2px(34f);
                    layoutParams4.width = DisplayUtils.dp2px(34f);
                    portrait4.setLayoutParams(layoutParams4);
                } else if (listGroup.size() == 3) {
                    holder.getView(R.id.rc_conversation_portrait1).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait2).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait3).setVisibility(View.VISIBLE);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(0).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait1), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(1).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait2), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(2).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait3), defaultId);
                    RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) portrait3.getLayoutParams();
                    layoutParams3.height = DisplayUtils.dp2px(34f);
                    layoutParams3.width = DisplayUtils.dp2px(34f);
                    layoutParams3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                    layoutParams3.addRule(RelativeLayout.CENTER_HORIZONTAL);
                    portrait3.setLayoutParams(layoutParams3);

                } else if (listGroup.size() == 4) {
                    holder.getView(R.id.rc_conversation_portrait1).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait2).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait3).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait4).setVisibility(View.VISIBLE);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(0).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait1), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(1).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait2), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(2).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait3), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(3).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait4), defaultId);
                } else {
                    holder.getView(R.id.rc_conversation_portrait1).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait2).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_portrait3).setVisibility(View.VISIBLE);
                    holder.getView(R.id.rc_conversation_user_count).setVisibility(View.VISIBLE);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(0).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait1), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(1).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait2), defaultId);
                    ImageLoadUtil.loadIv(holder.getContext(), listGroup.get(2).getAvatar(),
                            holder.getView(R.id.rc_conversation_portrait3), defaultId);
                    ((TextView) holder.getView(R.id.rc_conversation_user_count)).setText("+" + listGroup.size());
                }
            }

            ImageLoadUtil.loadIv(holder.getContext(), defaultId, holder.getView(R.id.rc_conversation_portrait));
        }

        //设置发送失败and发送中的状态
        ((TextView) holder.getView(R.id.rc_conversation_content)).setCompoundDrawables(null, null, null, null);
        if (uiConversation.mCore.getSentStatus() != null && TextUtils.isEmpty(uiConversation.mCore.getDraft()) && !TextUtils.isEmpty(uiConversation.mConversationContent)) {
            Drawable drawable = null;
            if (uiConversation.mCore.getSentStatus() == Message.SentStatus.FAILED) {
                drawable = ContextCompat.getDrawable(holder.getContext(), R.drawable.rc_ic_warning);
            } else if (uiConversation.mCore.getSentStatus() == Message.SentStatus.SENDING) {
                drawable = ContextCompat.getDrawable(holder.getContext(), R.drawable.rc_conversation_list_msg_sending);
            }

            if (drawable != null) {
                Bitmap bitmap = BitmapFactory.decodeResource(holder.getContext().getResources(), R.drawable.rc_ic_warning);
                int width = bitmap.getWidth();
                drawable.setBounds(0, 0, width, width);
                ((TextView) holder.getView(R.id.rc_conversation_content)).setCompoundDrawablePadding(10);
                ((TextView) holder.getView(R.id.rc_conversation_content)).setCompoundDrawables(drawable, null, null, null);
            }
        }

        //设置消息未读数量
        int unreadCount = uiConversation.mCore.getUnreadMessageCount();

        TUITextView tvUnRead = holder.getView(R.id.tv_unread_count);
        tvUnRead.getPaint().setFakeBoldText(true);
        tvUnRead.setVisibility(unreadCount > 0 ? View.VISIBLE : View.GONE);
        tvUnRead.setText(unreadCount > 99 ? "99+" : String.valueOf(unreadCount));

        //设置用户昵称标题颜色
        holder.title.setTextColor(ContextCompat.getColor(holder.getContext(), R.color.white));

        //设置用户消息内容的颜色，判断是否语音消息
        int defaultContentColor = Color.parseColor("#7D7D7D");
        int voiceContentColor = Color.parseColor("#FF3636");

        holder.content.setTextColor(defaultContentColor);
        holder.content.setTag(R.id.message_id, conversation.getLatestMessageId());
        if (messageContent instanceof HQVoiceMessage && !isGather) {
            getLastMessage(uiConversation, messages -> {
                UiMessage uiMessage = new UiMessage(messages);
                if (null != uiMessage) {
                    String extra = uiMessage.getExtra();
                    int messageId = (int) holder.content.getTag(R.id.message_id);
                    if (!TextUtils.equals(extra, "1") && messageId == conversation.getLatestMessageId()) {
                        holder.content.setTextColor(voiceContentColor);
                    }
                }
            });
        }

        //设置会话时间
        String time = RongDateUtils.getConversationListFormatDate(uiConversation.mCore.getSentTime(), holder.getContext());
        holder.time.setText(time);

        //设置消息内容
        //判断是否有草稿 || 被@的次数
        if (!TextUtils.isEmpty(uiConversation.mCore.getDraft()) || uiConversation.mCore.getMentionedCount() > 0) {
            holder.content.setEllipsize(null);
            if (uiConversation.mCore.getMentionedCount() > 0) {
                handleMentionedContent(holder, uiConversation);
            } else {
                handleDraftContent(holder, uiConversation);
            }
        } else {
            holder.content.setEllipsize(TextUtils.TruncateAt.END);
            //正常消息内容处理
            if (holder.getContext().getString(R.string.no_reply_message).equals(uiConversation.mCore.getConversationTitle()) && isGather) {
                SpannableString mConversationContent = new SpannableString(holder.getContext().getString(R.string.long_time_unread_msg_desc));
                holder.content.setText(mConversationContent, TextView.BufferType.SPANNABLE);
                holder.content.setTextColor(defaultContentColor);
            } else {
                handleCommonContent(holder, uiConversation);
            }
        }
    }

    /**
     * 设置标题 处理自定义消息
     */
    private void setTitle(BaseUiConversation data, Context context) {

        String senderId = data.mCore.getSenderUserId();
        String conversationTitle = data.mCore.getConversationTitle();
        Spannable mConversationContent = data.mConversationContent;

        if (TYPE_INTERACTIVE_MESSAGE.equals(senderId)) {
            conversationTitle = context.getString(R.string.interactive_notice);
        } else if (TYPE_ACCOUNT_SYSTEM.equals(senderId)) {
            conversationTitle = context.getString(R.string.office_notice);
        } else if (TYPE_ACCOUNT_PAY.equals(senderId)) {
            conversationTitle = context.getString(R.string.pay_helper);
            mConversationContent = new SpannableString(context.getString(R.string.pay_helper_desc));
        }

        data.mCore.setConversationTitle(conversationTitle);
        data.mConversationContent = mConversationContent;
    }

    /**
     * 获取自定义消息的最后一条消息
     */
    public void getLastMessage(BaseUiConversation data, LastMessageResultCallback callback) {
        RongIMClient.getInstance().getHistoryMessages(data.mCore.getConversationType(), data.mCore.getTargetId(), -1, 1, new RongIMClient.ResultCallback<List<Message>>() {
            @Override
            public void onSuccess(List<Message> messages) {
                for (int i = 0; i < messages.size(); i++) {
                    if (data.mCore.getLatestMessageId() == messages.get(i).getMessageId()) {
                        callback.onSuccess(messages.get(i));
                    }
                }
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {

            }
        });
    }

    /**
     * 最后一条消息的接口
     */
    public interface LastMessageResultCallback {
        void onSuccess(Message var1);
    }

    /**
     * @ 我的消息内容处理
     */
    private void handleMentionedContent(final ViewHolder holder, final BaseUiConversation data) {
        final String preStr = holder.getContext().getString(io.rong.imkit.R.string.rc_message_content_mentioned);
        SpannableStringBuilder builder = handleSpannableString(preStr + " " + data.mConversationContent, preStr, holder.getContext().getResources().getColor(R.color.rc_mentioned_color));
        AndroidEmoji.ensure(builder);
        holder.content.setText(builder, TextView.BufferType.SPANNABLE);
    }

    /**
     * 草稿消息内容处理
     */
    private void handleDraftContent(final ViewHolder holder, final BaseUiConversation data) {
        String preStr = holder.getContext().getString(io.rong.imkit.R.string.rc_message_content_draft);
        preStr = "";
        SpannableStringBuilder builder = handleSpannableString(preStr + " " + data.mConversationContent, preStr, holder.getContext().getResources().getColor(R.color.rc_mentioned_color));
        AndroidEmoji.ensure(builder);
        holder.content.setText(builder, TextView.BufferType.SPANNABLE);
    }

    /**
     * 正常聊天消息内容处理
     */
    private void handleCommonContent(final ViewHolder holder, final BaseUiConversation data) {
        try {
            final CharSequence cutStr;

            MessageExtraInfo messageExtraInfo = UnReplyMessageUtils.getMessageContent(data.mCore.getTargetId());
            if (null != messageExtraInfo && messageExtraInfo.getConversationContent() != null) {
                cutStr = messageExtraInfo.getConversationContent();
            } else {
                cutStr = data.mConversationContent;
            }


            String extra = data.mCore.getLatestMessage().getExtra();
            if (extra != null && !"".equals(extra) && !"{}".equals(extra)) {
                ContentTranslateBean translateBean = JSONObject.parseObject(extra, ContentTranslateBean.class);
                holder.content.setText(translateBean.getContentTranslate(), TextView.BufferType.SPANNABLE);
            } else {
                holder.content.setText(cutStr, TextView.BufferType.SPANNABLE);
                if ("".equals(cutStr.toString())) {
                    holder.content.setText(getLastMessage(data.mCore.getLatestMessage()));
                }
            }

            if (data.mCore.getObjectName().equals(GROUP_CREATE)) {
                holder.content.setText("「群聊邀请」");
            }

            if (data.mCore.getObjectName().equals(GROUP_KICK)) {
                holder.content.setText("「用户移出群聊」");
            }

            if (data.mCore.getObjectName().equals(GROUP_EDIT_NAME)) {
                holder.content.setText("「群名称修改」");
            }

            if (data.mCore.getObjectName().equals(GROUP_JOIN_MESSAGE)) {
                holder.content.setText("「用户加入群聊」");
            }

            if (data.mCore.getObjectName().equals(GROUP_QUIT_MESSAGE)) {
                holder.content.setText("「用户退出群聊」");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置文字高亮
     */
    private SpannableStringBuilder handleSpannableString(String content, String highlight, int color) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        if (TextUtils.isEmpty(content)) {
            return builder;
        }

        SpannableString string = new SpannableString(content);
        builder.append(string);
        if (TextUtils.isEmpty(highlight)) {
            return builder;
        }

        int end = highlight.length();
        if (end > content.length()) {
            end = content.length();
        }
        string.setSpan(new ForegroundColorSpan(color), 0, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return builder;
    }

    private int getSystemDefaultId(BaseUiConversation data, int defaultId) {
        switch (data.mCore.getSenderUserId()) {
            case TYPE_INTERACTIVE_MESSAGE:
                // 互动消息
                defaultId = R.mipmap.icon_company_notice;
                break;
            case TYPE_ACCOUNT_SYSTEM:
                // 系统消息
                defaultId = R.mipmap.icon_company_notice;
                break;
            case TYPE_ACCOUNT_PAY:
                // 支付助手
                defaultId = R.mipmap.icon_assistant_pay;
                break;
            default:
                break;
        }
        return defaultId;
    }

    /**
     * 获取最后一条消息
     */
    private String getLastMessage(MessageContent lastMessage) {
        return "";
    }
}